﻿using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;

namespace FlyingEye.EntityFrameworkCore
{
    /* This class is needed for EF Core console commands
     * (like Add-Migration and Update-Database commands) */
    public class DeviceOpsServiceDbContextFactory : IDesignTimeDbContextFactory<DeviceOpsServiceDbContext>
    {
        public DeviceOpsServiceDbContext CreateDbContext(string[] args)
        {
            DeviceOpsServiceEfCoreEntityExtensionMappings.Configure();

            var configuration = BuildConfiguration();
            var connectionString = configuration.GetConnectionString("DeviceOpsService");

            Console.WriteLine($"DeviceOpsService Database: {connectionString}");

            var builder = new DbContextOptionsBuilder<DeviceOpsServiceDbContext>();

            builder.UseMySql(connectionString, ServerVersion.Parse("8.1"));
            
            return new DeviceOpsServiceDbContext(builder.Options);
        }

        private static IConfigurationRoot BuildConfiguration()
        {
            var basePath = Path.Combine(Path.Combine(Directory.GetCurrentDirectory(), "../FlyingEye.DeviceOpsService.DbMigrator/"));

            Console.WriteLine($"Base Path: {Path.GetFullPath(basePath)}");
#if DEBUG
            var builder = new ConfigurationBuilder()
                .SetBasePath(basePath)
                .AddJsonFile("appsettings.Development.json", optional: false);
#else
            var builder = new ConfigurationBuilder()
                .SetBasePath(basePath)
                .AddJsonFile("appsettings.json", optional: false);
#endif

            return builder.Build();
        }
    }
}
